import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import styles from './index.less';
import { message, Spin, Button } from 'antd';
import { useSetState } from 'ahooks';
import moment from 'moment';

import { TRAlert } from '#/components/index.js';
import { HttpCode } from '#/utils/contacts.js';
// import StrategicBenefitEstimation from './components/StrategicBenefitEstimation';
import AdjustPolicyEditing from './components/AdjustPolicyEditing';
import OperationLog from './components/OperationLog';
import OutputPlanOperationLog from './components/OutputPlanOperationLog/index.jsx';
import PriceDiffCurve from './components/PriceDiffCurve';
import ForecastAndSimulate from './components/ForecastAndSimulate';
import ReferenceStrategy from './components/ReferenceStrategy';
import ChartsForecast from './components/ChartsForecast';
import OutputPlan from './components/OutputPlan/index.jsx';
import {
  postQueryPriceDiffCurve,
  postQueryForecastAndSimulate,
  postQueryRateData,
  postAdjustProportionData,
  postFindAIRateData,
  // postFindStrategyPriceForecast,
  // postFindStrategyPriceForecastAI,
  postGetSpotPriceDifferencePriceForecast,
  postQueryLastQuoteStation,
  manualStrategySaveDataStatus,
  queryForecastAndManualStrategy,
  enableAI,
  queryProvincialSpotBiddingPlan,
} from '../service';
import { ExplainTitle } from '../components/index';
import { titleMap, defaultPointerNum, defaultSourceTypeSpecial } from '../dictionary';
import type {
  IFormValue,
  IPostQueryPriceDiffCurveParamsType,
  IComponentsIsLoadingType,
  IComponentsIsErrorType,
  IPostQueryForecastAndSimulateParamsType,
  IDataListType,
  IDataSourceListType,
  IPriceDiffCurveDataType,
  IPostFindAIRateDataParamsType,
  IPostFindStrategyPriceForecastParamsType,
  IForecastAndSimulateDataType,
  IFindStrategyPriceForecastDataType,
  IReferenceStrategyDataType,
  IPostQueryForecastAndSimulateParamsNewType,
} from '../type';

import {
  IUseType,
  ITitleType,
  ISourceType,
  IValueType,
  IBaseValueType,
  ICorrectionType,
  ISmoothStatusType,
  IStoreType,
  IForecastAndSimulateChartsLineType,
  IShorttermForecastingRedesignPermissions,
  IResetType,
  IStepsType,
} from '../type';
import { TIME_ENUM, havePermissions, ToFixed, maxTotalReward } from '../tool';

interface IProps {
  /**
   * menuCode
   */
  menuCode?: string;
  /**
   * 请求数据
   */
  formValue?: IFormValue;
  /**
   * 是否需要重新刷新数据
   */
  activeKey?: number;
  /**
   * 权限
   */
  buttonPermissions?: any;
  /**
   * 禁用保存按钮
   */
  saveButtonDisabled?: boolean;
  /**
   * IStepsType
   */
  activeStep?: IStepsType;
  /**
   * AI策略默认信参数
   */
  aiStrategyData?: any;
  /**
   * 场站权限数据
   */
  power?: any;
}

const Strategy = forwardRef((props: IProps, ref) => {
  const {
    formValue,
    activeKey,
    menuCode,
    buttonPermissions,
    saveButtonDisabled,
    activeStep,
    aiStrategyData,
    power,
  } = props;

  const [userChartData, setUserChartData] = useState<IForecastAndSimulateDataType[]>([]);
  const [switchState, setSwitchState] = useState<any>(null); //开关状态
  const [resetState, setResetState] = useState<number>(0); //重置状态
  const [userLoading, setUserLoading] = useState<boolean>(false);

  const contentRef: any = useRef(null);
  const isQuantityQuotation = formValue?.quantityQuotation === 0;
  const pointerNums = TIME_ENUM(defaultPointerNum);
  const [loading, setLoading] = useState<boolean>(false);
  const [visible, setVisible] = useState<boolean>(false);
  const [priceDiffCurveparams, setPriceDiffCurveparams] =
    useState<IPostQueryPriceDiffCurveParamsType>();
  const [forecastAndSimulateParams, setForecastAndSimulateParams] =
    useState<IPostQueryForecastAndSimulateParamsType>();
  const [priceDiffCurveData, setPriceDiffCurveData] = useState<IPriceDiffCurveDataType>({});
  const [forecastAndSimulateData, setForecastAndSimulateData] = useState<
    IForecastAndSimulateDataType[]
  >([]);
  // const [findStrategyPriceForecastData, setFindStrategyPriceForecastData] =
  //   useSetState<IFindStrategyPriceForecastDataType>({});
  const [adjustPolicyEditingData, setAdjustPolicyEditingData] = useState<IDataListType[]>([]);
  const [dataSourceList, setDataSourceList] = useState<IDataSourceListType[]>([]);
  const [defaultDataSourceId, setDefaultDataSourceId] = useState<number>();
  const [smoothStatus, setSmoothStatus] = useState<ISmoothStatusType | null>(null);
  const [quoteStationId, setQuoteStationId] = useState<number | null>(null);
  const [defaultCapacity, setDefaultCapacity] = useState<number | string>();
  const [outputPlanData, setOutputPlanData] = useState<any>({});
  const [componentsIsLoading, setComponentsIsLoading] = useSetState<IComponentsIsLoadingType>({
    priceDiffCurveIsLoading: false,
    forecastAndSimulateIsLoading: false,
    adjustPolicyEditingIsLoading: false,
    adjustPolicyEditingIsButtonLoading: false,
    strategicBenefitEstimationIsLoading: false,
    strategicBenefitEstimationAiIsLoading: false,
    aiForecastIsLoading: false,
    resetButIsLoading: false,
  });
  const [componentsIsError, setComponentsIsError] = useSetState<IComponentsIsErrorType>({
    priceDiffCurveIsError: false,
    forecastAndSimulateIsError: false,
    forecastAndSimulateFail: false,
    adjustPolicyEditingIsError: false,
    strategicBenefitEstimationIsError: false,
    strategicBenefitEstimationAIIsError: false,
  });

  // 策略效益预估
  const findStrategyPriceForecast = async (
    params: IPostFindStrategyPriceForecastParamsType,
    isReset = false,
  ) => {
    if (isReset) {
      setComponentsIsLoading({
        resetButIsLoading: true,
      });
    } else {
      setComponentsIsLoading({
        strategicBenefitEstimationIsLoading: true,
        strategicBenefitEstimationAiIsLoading: true,
      });
    }
    // findNowStrategyPriceForecast(params);
    // findAiStrategyPriceForecast(params);
    setComponentsIsLoading({
      resetButIsLoading: false,
    });
  };

  // 功率预测及模拟调整
  const queryForecastAndSimulate = async (
    params: IPostQueryForecastAndSimulateParamsType,
    queryfindStrategyPriceForecastParams?: {
      baseValue: IBaseValueType;
      correction: ICorrectionType;
      dataSourceId: number;
      priceDiffCurveData: IPriceDiffCurveDataType;
    },
    isUserFetchData?: boolean,
  ) => {
    setComponentsIsLoading({
      forecastAndSimulateIsLoading: true,
    });
    const userParams: IPostQueryForecastAndSimulateParamsNewType = {
      ...params,
      dataFrom: switchState ? 8 : 9, //8, "-启用AI" \ 9, "-人工"
      smoothStatus: params.smoothStatus !== ISmoothStatusType.NONE ? params.smoothStatus : null,
    };

    userFetchData(userParams);

    // 控制调整模拟数据查询
    if (isUserFetchData) {
      const _params: IPostQueryForecastAndSimulateParamsType = {
        ...params,
        smoothStatus: params.smoothStatus !== ISmoothStatusType.NONE ? params.smoothStatus : null,
      };
      const res = await postQueryForecastAndSimulate(_params);
      if (res && res.statusCode === HttpCode.SUCCESS) {
        setComponentsIsError({
          forecastAndSimulateIsError: false,
          forecastAndSimulateFail: false,
        });
        setForecastAndSimulateData(res?.data || []);
        if (queryfindStrategyPriceForecastParams) {
          const _priceDiffbelieve =
            priceDiffCurveparams?.baseValue === IBaseValueType.BASE
              ? priceDiffCurveData?.baseAfter?.priceDiffbelieve
              : priceDiffCurveData?.noBaseAfter?.priceDiffbelieve;
          const _realTimeDayAheadPriceDiff =
            priceDiffCurveparams?.baseValue === IBaseValueType.BASE
              ? priceDiffCurveData?.baseAfter?.dayAheadPriceDiff
              : priceDiffCurveData?.noBaseAfter?.realTimeDayAheadPriceDiff;
          const _realTimePrice =
            priceDiffCurveparams?.baseValue === IBaseValueType.BASE
              ? priceDiffCurveData?.baseAfter?.realTimePrice
              : priceDiffCurveData?.noBaseAfter?.realTimePrice;
          const _dayAheadForecastPrice =
            priceDiffCurveparams?.baseValue === IBaseValueType.BASE
              ? priceDiffCurveData?.baseAfter?.dayAheadPrice
              : priceDiffCurveData?.noBaseAfter?.dayAheadForecastPrice;
          const _basePersent =
            priceDiffCurveparams?.correction === ICorrectionType.BEFORE
              ? priceDiffCurveData?.baseBefore?.basePersent
              : priceDiffCurveData?.baseAfter?.basePersent;
          const _findStrategyPriceForecastParams: IPostFindStrategyPriceForecastParamsType = {
            adjustmentElectric:
              res?.data?.find(
                (item: IForecastAndSimulateDataType) =>
                  item.dataSource === IForecastAndSimulateChartsLineType.LINE_TWO,
              )?.values || [],
            calendarDate: formValue?.calendarDate,
            priceDiffbelieve:
              (_priceDiffbelieve?.map((item) =>
                item.value === '-' ? null : item.value,
              ) as number[]) || [],
            provinceId: formValue?.provinceId,
            rateList: params?.dataList,
            realTimeDayAheadPriceDiff:
              (_realTimeDayAheadPriceDiff?.map((item) =>
                item.value === '-' ? null : item.value,
              ) as number[]) || [],
            realTimePrice: (_realTimePrice?.map((item) => item.value) as number[]) || [],
            stationId: formValue?.stationId,
            smoothStatus:
              params.smoothStatus !== ISmoothStatusType.NONE ? params.smoothStatus : null,
            dayAheadForecastPrice:
              (_dayAheadForecastPrice?.map((item) =>
                item.value === '-' ? null : item.value,
              ) as number[]) || [],
            basePersent:
              (_basePersent?.map((item) => (item.value === '-' ? null : item.value)) as number[]) ||
              [],
            forcastPower:
              res?.data?.find(
                (item: IForecastAndSimulateDataType) =>
                  item.dataSourceId === queryfindStrategyPriceForecastParams?.dataSourceId,
              )?.values || [],
          };
          findStrategyPriceForecast(_findStrategyPriceForecastParams);
        }
      } else if (res && res.statusCode === '1007') {
        setComponentsIsError({
          forecastAndSimulateIsError: true,
          forecastAndSimulateFail: true,
        });
        message.error(res?.message || '系统异常');
      } else {
        setComponentsIsError({
          forecastAndSimulateIsError: true,
        });
        message.error(res?.message || '系统异常');
      }
    }
    setComponentsIsLoading({
      strategicBenefitEstimationIsLoading: false,
      strategicBenefitEstimationAiIsLoading: false,
    });
    setForecastAndSimulateParams(params);
    setComponentsIsLoading({
      forecastAndSimulateIsLoading: false,
    });
  };

  const mockData = ({ upperLimitPrice, lowerLimitPrice, stationCapacity }: any) => {
    return [
      // {
      //   startOutput: 0,
      //   electricityPrice: 0,
      //   upperLimitPrice,
      //   lowerLimitPrice,
      // },
      {
        startOutput: 0,
        endOutput: stationCapacity,
        electricityPrice: lowerLimitPrice || 0,
        upperLimitPrice,
        lowerLimitPrice,
      },
    ];
  };

  const getTableData = (data: any) => {
    return data.map((t: any, i: any) => ({ ...t, index: i }));
  };

  const queryPlanData = async (params: any, type = '方案') => {
    const { stationId } = params;
    setComponentsIsLoading({
      adjustPolicyEditingIsLoading: true,
    });
    try {
      const res = await queryProvincialSpotBiddingPlan({ stationId });
      if (res && res.statusCode === HttpCode.SUCCESS) {
        const { planList = [], defaultPlanList = [] } = res?.data;

        const data = getTableData(planList.length ? planList : mockData(res?.data));
        const defaultData = getTableData(
          defaultPlanList.length ? defaultPlanList : mockData(res?.data),
        );

        setOutputPlanData({
          ...res?.data,
          planList: data,
          defaultPlanList: defaultData,
        });
        setComponentsIsError({
          adjustPolicyEditingIsError: false,
        });
      } else {
        setComponentsIsError({
          adjustPolicyEditingIsError: true,
        });
        message.error(res?.message || '系统异常');
      }
    } catch (e) {
      setComponentsIsError({
        adjustPolicyEditingIsError: true,
      });
      message.error(e || '系统异常');
    } finally {
      setComponentsIsLoading({
        adjustPolicyEditingIsLoading: false,
      });
    }
  };

  // 调整策略编辑列表数据
  const queryRateData = async (
    params?: IFormValue,
    smoothStatusValue?: ISmoothStatusType | null,
    initChecked?: boolean,
  ) => {
    setComponentsIsLoading({
      adjustPolicyEditingIsLoading: true,
    });

    const _params = {
      markDate: formValue?.calendarDate,
      stationId: formValue?.stationId ? Number(formValue.stationId) : undefined,
    };

    if (switchState == true || initChecked == true) {
      const res = await enableAI(_params || {});
      if (res && res.statusCode === HttpCode.SUCCESS) {
        setComponentsIsError({
          adjustPolicyEditingIsError: false,
        });
        const { dataList = [] } = res || {};
        const _adjustPolicyEditingData: IDataListType[] = (dataList || []).map(
          (item: IDataListType, index: number) => {
            return {
              ...item,
              beginTime: pointerNums[item?.beginIndex ?? 0] ?? '',
              endTime: pointerNums[item?.endIndex ?? 0] ?? '',
              maxValue: item?.maxValue ?? defaultCapacity,
              minValue: item?.minValue ?? '0.000',
              fixedValue: item?.fixedValue ?? '0.000',
              id: index + 1,
            };
          },
        );
        setAdjustPolicyEditingData(_adjustPolicyEditingData);
        const _dataList: any[] = _adjustPolicyEditingData.map((item: IDataListType) => {
          const { id, beginTime, endTime, ...rest } = item;
          return {
            ...rest,
          };
        });
        const _queryForecastAndSimulateParams: IPostQueryForecastAndSimulateParamsType = {
          dataList: _dataList,
          markDate: params?.calendarDate,
          quoteStationId: quoteStationId ?? undefined,
          smoothStatus: smoothStatusValue ?? smoothStatus,
          stationId: params?.stationId ? Number(params?.stationId) : undefined,
          store: IStoreType.NO_CONSIDER,
        };
        queryForecastAndSimulate(_queryForecastAndSimulateParams, undefined, true);
      } else {
        setComponentsIsError({
          adjustPolicyEditingIsError: true,
        });
        message.error(res?.message || '系统异常');
      }
    } else if (switchState == false || initChecked == false) {
      const _params = {
        ...params,
        reset: resetState,
      };
      // @ts-ignore
      const res = await postQueryRateData(_params || {});
      if (res && res.statusCode === HttpCode.SUCCESS) {
        setComponentsIsError({
          adjustPolicyEditingIsError: false,
        });
        const {
          dataList = [],
          // eslint-disable-next-line @typescript-eslint/no-shadow
          // smoothStatus = ISmoothStatusType.BEZIER,
          // eslint-disable-next-line @typescript-eslint/no-shadow
          defaultCapacity = '0.000',
          // eslint-disable-next-line @typescript-eslint/no-shadow
          dataSourceList = [],
          // eslint-disable-next-line @typescript-eslint/no-shadow
          quoteStationId = null,
          // eslint-disable-next-line @typescript-eslint/no-shadow
          defaultDataSourceId,
        } = res?.data || {};
        const _adjustPolicyEditingData: IDataListType[] = (dataList || []).map(
          (item: IDataListType, index: number) => {
            return {
              ...item,
              beginTime: pointerNums[item?.beginIndex ?? 0] ?? '',
              endTime: pointerNums[item?.endIndex ?? 0] ?? '',
              maxValue: item?.maxValue ?? defaultCapacity,
              minValue: item?.minValue ?? '0.000',
              fixedValue: item?.fixedValue ?? '0.000',
              id: index + 1,
            };
          },
        );
        setDefaultDataSourceId(defaultDataSourceId);
        setDefaultCapacity(defaultCapacity ?? '0.000');
        setDataSourceList(dataSourceList || []);
        setAdjustPolicyEditingData(_adjustPolicyEditingData);
        setQuoteStationId(quoteStationId);
        const _dataList: any[] = _adjustPolicyEditingData.map((item: IDataListType) => {
          const { id, beginTime, endTime, ...rest } = item;
          return {
            ...rest,
          };
        });
        const _queryForecastAndSimulateParams: IPostQueryForecastAndSimulateParamsType = {
          dataList: _dataList,
          markDate: params?.calendarDate,
          quoteStationId: quoteStationId,
          smoothStatus: smoothStatusValue ?? smoothStatus,
          stationId: params?.stationId ? Number(params?.stationId) : undefined,
          store: IStoreType.NO_CONSIDER,
        };

        queryForecastAndSimulate(_queryForecastAndSimulateParams, undefined, true);
      } else {
        setComponentsIsError({
          adjustPolicyEditingIsError: true,
        });
        message.error(res?.message || '系统异常');
      }
    }

    setLoading(false);
    setComponentsIsLoading({
      adjustPolicyEditingIsLoading: false,
    });
  };

  const dealData = (val: any, key1: string, key2: string) => {
    if (val && val[key1] && val[key1][key2]) {
      const pointerList = TIME_ENUM(defaultPointerNum, 'HH:mm');
      const list: any = Object.values(val[key1][key2])[0] ? Object.values(val[key1][key2])[0] : {};
      const _data = pointerList.map((item, index) => {
        return {
          timeOrder: index,
          value: list[item] || '-',
        };
      });
      return _data;
    } else {
      return [];
    }
  };

  // 查询价差曲线
  const queryPriceDiffCurve = async (params: IPostQueryPriceDiffCurveParamsType) => {
    setComponentsIsLoading({
      priceDiffCurveIsLoading: true,
    });
    let baseValue = IBaseValueType.NO_BASE,
      baseValueText: string = '-1';
    if (params?.sourceType === ISourceType.HISTORY) {
      const res = await postQueryPriceDiffCurve(params);
      if (res && res.statusCode === HttpCode.SUCCESS) {
        setComponentsIsError({
          priceDiffCurveIsError: false,
        });
        // setPriceDiffCurveData({ ...res?.data } || {});
        setPriceDiffCurveData(res.data ? { ...res.data } : {});
      } else {
        setComponentsIsError({
          priceDiffCurveIsError: true,
        });
        setComponentsIsLoading({
          strategicBenefitEstimationIsLoading: false,
          strategicBenefitEstimationAiIsLoading: false,
        });
        message.error(res?.message || '系统异常');
      }
    } else {
      const _params = {
        endDate: params?.calendarDate,
        provinceId: params?.provinceId,
        startDate: params?.calendarDate,
        stationId: params?.stationId,
      };
      const res = await postGetSpotPriceDifferencePriceForecast(_params);

      if (res && res.statusCode === HttpCode.SUCCESS) {
        setComponentsIsError({
          priceDiffCurveIsError: false,
        });

        // 修改接口取消了 状态无基数-修正前、无基数-修正后、有基数-修正前、有基数-修正后
        const _data = {
          newChartData: {
            dayAheadForecastPrice: dealData(
              res?.spotPriceDataMap,
              'clearDifferencePriceForecast',
              'dayAheadPriceForecast',
            ),
            priceDiffbelieve: dealData(
              res?.spotPriceDataMap,
              'clearDifferencePriceForecast',
              'priceDifferenceConfidence',
            ),
            realTimeDayAheadPriceDiff: dealData(
              res?.spotPriceDataMap,
              'clearDifferencePriceForecast',
              'priceDifferenceForecast',
            ),
            realTimePrice: dealData(
              res?.spotPriceDataMap,
              'clearDifferencePriceForecast',
              'realtimePriceForecast',
            ),
            // basePersent:
            // dealData(
            //   res?.spotPriceDataMap,
            //   'clearDifferencePriceForecast',
            //   'baseRatioForecast',
            // ),
          },
        };
        const _list = {
          newChartData:
            _data?.newChartData?.dayAheadForecastPrice?.length ||
            _data?.newChartData?.priceDiffbelieve?.length ||
            _data?.newChartData?.realTimeDayAheadPriceDiff?.length ||
            _data?.newChartData?.realTimePrice?.length
              ? _data?.newChartData
              : undefined,
        };

        setPriceDiffCurveData(_list || {});
        // baseValue = res.baseFlag === '0' ? IBaseValueType.NO_BASE : IBaseValueType.BASE;

        // 取消了基数
        baseValue = IBaseValueType.NO_BASE;
        baseValueText = String(res.baseFlag);
      } else {
        setComponentsIsError({
          priceDiffCurveIsError: true,
        });
        setComponentsIsLoading({
          strategicBenefitEstimationIsLoading: false,
          strategicBenefitEstimationAiIsLoading: false,
        });
        message.error(res?.message || '系统异常');
      }
    }
    setPriceDiffCurveparams({ ...params, baseValue, baseValueText });
    setLoading(false);
    setComponentsIsLoading({
      priceDiffCurveIsLoading: false,
    });
  };

  // 初始化
  const fetchData = async (formValue1: IFormValue) => {
    const { provinceId, quantityQuotation } = formValue1;
    setLoading(true);
    const _priceDiffCurveparams: IPostQueryPriceDiffCurveParamsType = {
      ...formValue1,
      sourceType:
        provinceId && defaultSourceTypeSpecial.includes(provinceId)
          ? ISourceType.TIAN_JI
          : ISourceType.HISTORY,
      // sourceType: ISourceType.HISTORY,
      valueType: IValueType.MEAN_VALUE,
      startDate: moment().subtract(7, 'day').format('YYYY-MM-DD'),
      endDate: moment().subtract(1, 'day').format('YYYY-MM-DD'),
      correction: ICorrectionType.AFTER,
    };
    await queryPriceDiffCurve(_priceDiffCurveparams);

    await queryRateData(formValue1);
    //报量报价
    if (!quantityQuotation) {
      await queryPlanData(formValue1);
    }
    setLoading(false);
  };

  // 引用策略
  const onReferenceStrategy = async () => {
    const res = await postQueryLastQuoteStation();
    await ReferenceStrategy.show({
      menuCode: menuCode,
      stationId: formValue?.stationId,
      quoteStationId: res?.data,
      formValue: formValue,
      onSubmit: (data: IReferenceStrategyDataType) => {
        // eslint-disable-next-line @typescript-eslint/no-shadow
        const { quoteDataList = [], quoteStationId } = data;
        const _adjustPolicyEditingData: IDataListType[] = [];
        quoteDataList.map((item: IDataListType, index: number) => {
          _adjustPolicyEditingData.push({
            ...item,
            dataSourceId: dataSourceList.find((i) => i.dataSourceId === item?.dataSourceId)
              ? item?.dataSourceId
              : defaultDataSourceId,
            beginTime: pointerNums[item?.beginIndex ?? 0] ?? '',
            endTime: pointerNums[item?.endIndex ?? 0] ?? '',
            maxValue: defaultCapacity,
            minValue: '0.000',
            fixedValue:
              Number(item?.fixedValue) > Number(defaultCapacity)
                ? defaultCapacity ?? '0.000'
                : item?.fixedValue ?? '0.000',
            id: index + 1,
          });
        });
        const _dataList: any[] = _adjustPolicyEditingData.map((item: IDataListType) => {
          const { id, beginTime, endTime, ...rest } = item;
          return {
            ...rest,
          };
        });
        const _queryForecastAndSimulateParams: IPostQueryForecastAndSimulateParamsType = {
          dataList: _dataList,
          markDate: formValue?.calendarDate,
          quoteStationId: quoteStationId,
          smoothStatus: smoothStatus,
          stationId: formValue?.stationId ? Number(formValue?.stationId) : undefined,
          store: IStoreType.NO_CONSIDER,
        };
        queryForecastAndSimulate(_queryForecastAndSimulateParams);
        setQuoteStationId(quoteStationId as unknown as number);
        // saveLastQuoteStation(quoteStationId);
        setAdjustPolicyEditingData(_adjustPolicyEditingData);
      },
    });
  };

  // 图形策略
  /*   const onReferenceChart = async () => {
    const _curveDataList =
      forecastAndSimulateData.find((item) => {
        return item.dataSource === IForecastAndSimulateChartsLineType.LINE_SIX;
      })?.values || [];
    if (_curveDataList.length > 0) {
      const _adjustPolicyEditingData: IDataListType[] = _curveDataList.map(
        (item: number, index: number) => {
          return {
            useType: IUseType.FIXATION,
            rateValue: 100,
            dataSourceId: defaultDataSourceId,
            beginTime: pointerNums[index ?? 0] ?? '',
            beginIndex: index,
            endIndex: index,
            endTime: pointerNums[index ?? 0] ?? '',
            maxValue: ToFixed(defaultCapacity, 3),
            minValue: '0.000',
            fixedValue:
              Number(item) > Number(defaultCapacity)
                ? ToFixed(defaultCapacity, 3) ?? '0.000'
                : ToFixed(item, 3) ?? '0.000',
            id: index + 1,
          };
        },
      );
      await ChartsForecast.show({
        data: _adjustPolicyEditingData,
        onSubmit: (val: IDataListType[]) => {
          const _dataList: any[] = val.map((item: IDataListType) => {
            const { id, beginTime, endTime, ...rest } = item;
            return {
              ...rest,
            };
          });
          const _queryForecastAndSimulateParams: IPostQueryForecastAndSimulateParamsType = {
            dataList: _dataList,
            markDate: formValue?.calendarDate,
            smoothStatus: smoothStatus,
            stationId: formValue?.stationId ? Number(formValue?.stationId) : undefined,
            store: IStoreType.NO_CONSIDER,
          };
          queryForecastAndSimulate(_queryForecastAndSimulateParams);
          setAdjustPolicyEditingData(val);
        },
      });
    } else {
      message.error('功率预测数据缺失!');
    }
  }; */

  // 改变平滑方式
  const onChangeSmoothWay = (e: ISmoothStatusType) => {
    setSmoothStatus(e);
    const _forecastAndSimulateParams = {
      ...forecastAndSimulateParams,
      smoothStatus: e,
    };
    queryForecastAndSimulate(_forecastAndSimulateParams);
  };

  // 重置调整策略编辑
  const onReset = (reset = IResetType.NO_RESET) => {
    setSwitchState(false);
    setSmoothStatus(ISmoothStatusType.BEZIER);
    setResetState(reset);
    setAdjustPolicyEditingData([]);
    setUserChartData([]);
    setOutputPlanData({});
    // @ts-ignore
    queryRateData({ ...formValue }, ISmoothStatusType.BEZIER);
    //报量报价
    if (isQuantityQuotation) {
      queryPlanData(formValue);
    }
  };

  // 保存调整策略编辑
  const onSave = async () => {
    const resoult = havePermissions(
      IShorttermForecastingRedesignPermissions.SAVEBUTTON,
      buttonPermissions,
    );
    if (resoult) {
      setComponentsIsLoading({
        adjustPolicyEditingIsButtonLoading: true,
      });
      if (isQuantityQuotation) {
        await contentRef?.current?.onSave?.();
        onReset();
      } else {
        await onSaveAdjustData();
      }
      setComponentsIsLoading({
        adjustPolicyEditingIsButtonLoading: false,
      });
    }
  };

  // 人工策略保存
  const onSaveAdjustData = async () => {
    let _adjustPolicyEditingData: IDataListType[] = adjustPolicyEditingData.map((item) => {
      const { beginTime, endTime, ...rest } = item;
      return {
        ...rest,
        beginIndex: pointerNums.findIndex((i) => i === beginTime),
        endIndex: pointerNums.findIndex((i) => i === endTime),
        timeSlot: `${beginTime}-${endTime}`,
      };
    });
    _adjustPolicyEditingData = _adjustPolicyEditingData.filter((item) => {
      return item.beginIndex !== -1 && item.endIndex !== -1;
    });
    const _params: IPostQueryForecastAndSimulateParamsNewType = {
      dataFrom: switchState ? 100 : 101, //100, "-启用AI" \ 101, "-人工"
      dataList: _adjustPolicyEditingData,
      markDate: formValue?.calendarDate,
      quoteStationId: quoteStationId ?? undefined,
      smoothStatus: smoothStatus,
      stationId: formValue?.stationId ? Number(formValue?.stationId) : undefined,
      store: IStoreType.NO_CONSIDER,
    };
    const res = await postAdjustProportionData(_params);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      setResetState(IResetType.NO_RESET);
      queryRateData(formValue || {});
      message.success(res.message || '保存成功');
    } else {
      message.error(res.message || '保存失败');
    }
  };

  // 调整策略编辑
  const onChangeAdjustPolicyEditingData = (data: IDataListType[], isRefresh: boolean = true) => {
    let _adjustPolicyEditingData: IDataListType[] = data.map((item) => {
      const { beginTime, endTime, ...rest } = item;
      return {
        ...rest,
        beginIndex: pointerNums.findIndex((i) => i === beginTime),
        endIndex: pointerNums.findIndex((i) => i === endTime),
        timeSlot: `${beginTime}-${endTime}`,
      };
    });
    _adjustPolicyEditingData = _adjustPolicyEditingData.filter((item) => {
      return item.beginIndex !== -1 && item.endIndex !== -1;
    });
    const _params: IPostQueryForecastAndSimulateParamsType = {
      dataList: _adjustPolicyEditingData,
      markDate: formValue?.calendarDate,
      quoteStationId: quoteStationId ?? undefined,
      smoothStatus: smoothStatus,
      stationId: formValue?.stationId ? Number(formValue?.stationId) : undefined,
      store: IStoreType.NO_CONSIDER,
    };
    setAdjustPolicyEditingData(data);
    if (isRefresh) {
      queryForecastAndSimulate(_params);
    }
  };

  // 关闭操作日志
  const onClose = () => {
    setVisible(false);
  };

  // AI策略开关
  const onChangeSwitchState = (checked: boolean) => {
    setSwitchState(checked);
  };

  // 获取人工策略数据
  const userFetchData = async (_params: IPostQueryForecastAndSimulateParamsType) => {
    setUserLoading(true);
    try {
      const res = await queryForecastAndManualStrategy(_params);
      if (res?.statusCode === HttpCode.SUCCESS) {
        setUserChartData(res.data);
        /* res.data.map((item: any, index: number) => {
          console.log(index + 'maxTotalReward' + item.dataSource, maxTotalReward(item.values));
        }); */
      } else {
        message.error(res?.message || '获取人工策略图表数据失败');
      }
    } catch (error) {
      message.error('数据请求失败');
    } finally {
      setUserLoading(false);
    }
  };

  // 默认平滑状态
  const defaultSmoothStatus = (values: ISmoothStatusType) => {
    if (values) {
      setSmoothStatus(values);
      return values;
    }
    return smoothStatus;
  };

  const getBtnStuatus = async () => {
    const _params: IPostQueryForecastAndSimulateParamsType = {
      markDate: formValue?.calendarDate,
      stationId: formValue?.stationId ? Number(formValue.stationId) : undefined,
    };
    const res = await manualStrategySaveDataStatus(_params);
    return res;
  };

  useImperativeHandle(ref, () => ({
    onReset,
  }));

  useEffect(() => {
    const disabled =
      componentsIsLoading.priceDiffCurveIsLoading ||
      componentsIsLoading.forecastAndSimulateIsLoading ||
      componentsIsLoading.adjustPolicyEditingIsLoading ||
      componentsIsLoading.resetButIsLoading ||
      componentsIsLoading?.aiForecastIsLoading ||
      componentsIsLoading.strategicBenefitEstimationIsLoading ||
      componentsIsLoading.strategicBenefitEstimationAiIsLoading;
    if (disabled) {
      message.info('数据请求中......');
    } else {
      if (
        formValue?.calendarDate &&
        formValue.provinceId &&
        formValue.stationId &&
        activeStep === IStepsType.STRATEGY
      ) {
        setComponentsIsLoading({
          priceDiffCurveIsLoading: true,
          forecastAndSimulateIsLoading: true,
          adjustPolicyEditingIsLoading: true,
        });
        // setFindStrategyPriceForecastData({
        //   currentStrategy: {},
        //   aiStrategy: {},
        // });
        fetchData(formValue);
      }
    }
  }, [activeKey]);

  /* useEffect(() => {
    const getData = async () => {
      setComponentsIsLoading({ adjustPolicyEditingIsButtonLoading: true });
      queryRateData({ ...formValue }).finally(() => {
        setComponentsIsLoading({ adjustPolicyEditingIsButtonLoading: false });
      });
    };

    if (switchState != null) {
      getData();
    }
  }, [resetState]); */

  useEffect(() => {
    const getData = async (smoothStatus: any, switchState: any) => {
      setComponentsIsLoading({ adjustPolicyEditingIsButtonLoading: true });
      try {
        await queryRateData({ ...formValue }, smoothStatus, switchState);
      } finally {
        setComponentsIsLoading({ adjustPolicyEditingIsButtonLoading: false });
      }
    };

    if (switchState != null && smoothStatus != null) {
      getData(smoothStatus, switchState);
    } else {
      getBtnStuatus().then((status) => {
        onChangeSwitchState(status.switchState || false);
        defaultSmoothStatus(status.smoothStatus || ISmoothStatusType.BEZIER);
        getData(status.smoothStatus, status.switchState);
      });
    }
  }, [switchState, resetState]);

  return (
    <div className={styles.container}>
      {loading ? (
        <Spin />
      ) : (
        <div className={styles.main}>
          <div className={styles.left}>
            <div className={styles.leftContent}>
              <div className={styles.priceDiffCurve}>
                <PriceDiffCurve
                  onSearch={queryPriceDiffCurve}
                  setPriceDiffCurveparams={setPriceDiffCurveparams}
                  priceDiffCurveparams={priceDiffCurveparams}
                  loading={componentsIsLoading.priceDiffCurveIsLoading}
                  error={componentsIsError.priceDiffCurveIsError}
                  data={priceDiffCurveData}
                  formValue={formValue}
                />
              </div>
              <div className={styles.forecastAndSimulate}>
                <ForecastAndSimulate
                  onSearch={queryForecastAndSimulate}
                  forecastAndSimulateParams={forecastAndSimulateParams}
                  loading={componentsIsLoading.forecastAndSimulateIsLoading}
                  error={componentsIsError.forecastAndSimulateIsError}
                  isFail={componentsIsError.forecastAndSimulateFail}
                  data={forecastAndSimulateData}
                  formValue={formValue}
                  buttonPermissions={buttonPermissions}
                  saveButtonDisabled={saveButtonDisabled}
                  menuCode={menuCode}
                  aiStrategyData={aiStrategyData}
                />
              </div>
            </div>
          </div>
          <div className={styles.right}>
            <div className={styles.rightBottom}>
              <div className={styles.header}>
                <div className={styles.title}>
                  <ExplainTitle title={titleMap[ITitleType.ADJUST_POLICY_EDITING].title} />
                  <div
                    className={styles.operationLog}
                    onClick={() => {
                      setVisible(true);
                    }}
                  >
                    <span className={styles.title}>操作日志</span>
                  </div>
                </div>
                <div className={styles.btnBox}>
                  <Button
                    className={styles.resetBut}
                    onClick={() => onReset(IResetType.RESET)}
                    loading={componentsIsLoading.adjustPolicyEditingIsButtonLoading}
                  >
                    重置
                  </Button>
                  <Button
                    className={styles.save}
                    onClick={onSave}
                    disabled={componentsIsError.adjustPolicyEditingIsError || saveButtonDisabled}
                    type="primary"
                    loading={componentsIsLoading.adjustPolicyEditingIsButtonLoading}
                  >
                    保存
                  </Button>
                </div>
              </div>
              <div className={styles.bottom}>
                {isQuantityQuotation ? (
                  <OutputPlan
                    ref={contentRef}
                    formValue={formValue}
                    power={power}
                    outputPlanData={outputPlanData}
                    buttonPermissions={buttonPermissions}
                    onFetch={queryPlanData}
                    aiStrategyData={aiStrategyData}
                  />
                ) : (
                  <AdjustPolicyEditing
                    smoothStatus={smoothStatus}
                    defaultSmoothStatus={defaultSmoothStatus}
                    defaultCapacity={defaultCapacity}
                    saveButtonDisabled={saveButtonDisabled}
                    data={adjustPolicyEditingData}
                    dataSourceList={dataSourceList}
                    error={componentsIsError.adjustPolicyEditingIsError}
                    userLoading={userLoading}
                    loading={componentsIsLoading.adjustPolicyEditingIsLoading}
                    buttonLoading={componentsIsLoading.adjustPolicyEditingIsButtonLoading}
                    aiForecastIsLoading={componentsIsLoading?.aiForecastIsLoading}
                    aiForecastIsDisabled={
                      componentsIsLoading.adjustPolicyEditingIsLoading ||
                      componentsIsLoading.forecastAndSimulateIsLoading
                    }
                    chartsForecastDisabled={componentsIsLoading.forecastAndSimulateIsLoading}
                    onChangeSmoothWay={onChangeSmoothWay}
                    // onReset={onReset}
                    onChange={onChangeAdjustPolicyEditingData}
                    onReferenceStrategy={onReferenceStrategy}
                    formValue={formValue}
                    aiStrategyData={aiStrategyData}
                    userChartData={userChartData}
                    switchState={switchState}
                    onChangeSwitchState={onChangeSwitchState}
                  />
                )}
              </div>
            </div>
          </div>
        </div>
      )}
      {isQuantityQuotation ? (
        <OutputPlanOperationLog visible={visible} onClose={onClose} formValue={formValue} />
      ) : (
        <OperationLog
          visible={visible}
          onClose={onClose}
          queryValue={{
            markDate: formValue?.calendarDate,
            stationId: formValue?.stationId,
            type: 2, //人工策略
          }}
        />
      )}
    </div>
  );
});

export default Strategy;
